﻿using System;
using System.IO;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using BikeBouncer.BusinessLayer;
using BikeBouncer.BusinessLayer.Entities;
using BikeBouncer.BusinessLayer.Enums;
using BikeBouncer.Site.Enums;

namespace BikeBouncer.Site
{
	public partial class MyBikes_aspx : BasePage
	{
		#region Properties

		private Int32 SelectedBikeId
		{
			get
			{
				return Convert.ToInt32(CboBikes.SelectedValue);
			}
		}

		private NoteCollection BikeNotes
		{
			get
			{
				Object obj = ViewState["BikeNotes"];

				if (obj == null)
				{
					return null;
				}

				return (NoteCollection)obj;
			}
			set
			{
				ViewState["BikeNotes"] = value;
			}
		}

		#endregion

		#region Page methods

		protected void Page_Load(Object sender, EventArgs e)
		{
			SessionManager.NeedsUserLogin();

			RegisterScript(ScriptSource.ColorPicker);
			RegisterScript(ScriptSource.ColorBox);

			LblBikeSaved.Text = String.Empty;

			if (!Page.IsPostBack)
			{
				AjaxManager.SetDefaults_AsyncFileUpload(UplBikePicture);

				LoadMyBikes();

				AddNote.AddressCity = SessionManager.CurrentCity;
				AddNote.AddressPhone = SessionManager.LoggedUser.Address.Phone;
			}
			else
			{
				if (SessionManager.CurrentItem == null)
				{
					SessionManager.CurrentItem = new Item(SelectedBikeId);
				}

				Page.Validate("Details");
			}
		}

		protected void Page_PreRender(Object sender, EventArgs e)
		{
			if (AddNote.AddedNoteId > 0)
			{
				LblBikeSaved.Text = GetLocalResourceObject("BikeNoteAdded") + " " + DateTime.Now.ToShortTimeString();

				AddNote.Clear();

				LoadSelectedBike();
			}

			PanBikeSaved.Visible = LblBikeSaved.Text.Length > 1;
		}

		#endregion

		#region Top bar

		private void LoadMyBikes()
		{
			ItemCollection bikes = new ItemCollection(DataAccess.Item_Get(SessionManager.LoggedUser));

			CboBikes.DataSource = bikes;
			CboBikes.DataBind();

			Int32 id = GetIdFromQuery("bike");

			if (bikes.Count == 1)
			{
				id = Convert.ToInt32(CboBikes.Items[0].Value);
			}

			ListItem i = CboBikes.Items.FindByValue(id.ToString());

			if (i != null)
			{
				i.Selected = true;

				LoadSelectedBike();
				PanDashboard.Visible = false;
			}

			if (PanDashboard.Visible)
			{
				LoadDashboard();
				PanBikeDetails.Visible = false;

				CboBikes.Items.Insert(0, new ListItem(GetLocalResourceObject("CboBikesSelect").ToString(), "0"));
				CboBikes.SelectedIndex = 0;
			}
		}

		#endregion

		#region Dashboard

		private void LoadDashboard()
		{
			LitBikesRegistered.Text = LitBikesRegistered.Text.Replace("#", CboBikes.Items.Count.ToString());
		}

		#endregion

		#region Load bike

		private void LoadSelectedBike()
		{
			Item item = new Item(SelectedBikeId);

			SessionManager.CurrentItem = item;

			AddNote.ItemId = item.Id;
			AddNote.UserId = SessionManager.LoggedUser.Id;

			LoadBikeStatus(item);
			LoadLastNotes(item);

			LblItemRegDate.Text = GetLocalResourceObject("LblItemRegDate.Text") + " " + item.RegDate.ToLongDateString();
			LblItemKeyValue.Text = item.Key;

			TxtItemTitle.Text = item.Title;
			TxtItemMaker.Text = item.Maker.Title;
			TxtItemSerial.Text = item.Serial;
			TxtItemDetails.Text = item.Details;

			TxtItemMaker.ReadOnly = TxtItemMaker.Text.Length > 1;
			TxtItemSerial.ReadOnly = TxtItemSerial.Text.Length > 1;

			ImgBikePicture.ImageUrl = item.PictureUrl;

			if (item.HasPicture)
			{
				LinkBikePicture.NavigateUrl = item.PictureUrl;
				LinkBikePicture.CssClass = "thickbox";
				LinkBikePicture.ToolTip = item.Summary;
			}

			ImgDataMatrix.ImageUrl = "/BarcodeImg.aspx?t=datamatrix&k=" + item.Key;
			ImgQRCode.ImageUrl = "/BarcodeImg.aspx?t=qrcode&k=" + item.Key;
		}

		private void LoadBikeStatus(Item item)
		{
			LblItemStatusValue.Text = GetLocalResourceObject("ItemStatus_" + item.Status).ToString();
			ImgItemStatus.ImageUrl = "/Images/Ico/Status" + (Int32)item.Status + "_24.png";

			AddNote.ItemStatus = Note.GetNextStatus(item);

			if (item.Status == ItemStatus.Lost || item.Status == ItemStatus.Stolen)
			{
				LinkTrackItem.NavigateUrl = "/BoxTrackItem.aspx?bike=" + SelectedBikeId;
				LinkTrackItem.ToolTip = GetLocalResourceObject("LinkTrackItem.ToolTip") + " (" + item.Title + ")";
				LinkTrackItem.Visible = true;
			}
			else
			{
				LinkTrackItem.Visible = false;
			}
		}

		#endregion

		#region Load notes

		protected void LinkNoteNewer_Click(Object sender, EventArgs e)
		{
			LinkNoteOlder.Enabled = true;

			for (Int32 i = 0; i < BikeNotes.Count; i++)
			{
				Int32 cur = (Int32)ViewState["CurrentNoteId"];

				if (BikeNotes[i].Id == cur)
				{
					LoadNote(i - 1);
					LinkNoteNewer.Enabled = i != 1;

					return;
				}
			}
		}

		protected void LinkNoteOlder_Click(Object sender, EventArgs e)
		{
			LinkNoteNewer.Enabled = true;

			for (Int32 i = 0; i < BikeNotes.Count; i++)
			{
				Int32 cur = (Int32)ViewState["CurrentNoteId"];

				if (BikeNotes[i].Id == cur)
				{
					LoadNote(i + 1);
					LinkNoteOlder.Enabled = i != BikeNotes.Count - 2;

					return;
				}
			}
		}

		private void LoadLastNotes(Item item)
		{
			BikeNotes = new NoteCollection(DataAccess.Note_Get(item, 20));

			if (BikeNotes.Count > 0)
			{
				LoadNote(0);

				if (BikeNotes.Count == 1)
				{
					LinkNoteOlder.Enabled = false;
				}

				LinkNoteNewer.Enabled = false;
				PanNotes.Visible = true;
			}
			else
			{
				PanNotes.Visible = false;
			}
		}

		private void LoadNote(Int32 index)
		{
			Note note = BikeNotes[index];
			String user = note.User.DisplayName;

			if (String.IsNullOrEmpty(user))
			{
				user = GetGlobalString("Anonymous");
			}

			ViewState["CurrentNoteId"] = note.Id;

			LitNoteDetails.Text = note.Details;
			LitNoteAddress.Text = note.Address.ToString(", ");
			LitNotePostedDate.Text = note.ReferenceDate.ToString("f");

			if (LitNoteAddress.Text.Length < 2)
			{
				LitNoteAddress.Text = GetLocalResourceObject("NoAddress").ToString();
			}

			LblNoteOwner.Text = user;

			LitNoteCurrent.Text = GetLocalResourceObject("LitNoteCurrent").ToString();
			LitNoteCurrent.Text = LitNoteCurrent.Text.Replace("#CURRENT#", (index + 1).ToString());
			LitNoteCurrent.Text = LitNoteCurrent.Text.Replace("#TOTAL#", BikeNotes.Count.ToString());
		}

		#endregion

		#region Update bike details

		protected void ButUpdateDetails_Click(Object sender, EventArgs e)
		{
			if (Page.IsValid)
			{
				Item item = SessionManager.CurrentItem;

				item.Title = TxtItemTitle.Text;
				item.Serial = TxtItemSerial.Text;
				item.Details = TxtItemDetails.Text;

				DataAccess.Item_Upsert(item);

				LblBikeSaved.Text = GetLocalResourceObject("BikeDetailsUpdated") + " " + DateTime.Now.ToShortTimeString();
			}
		}

		#endregion

		#region Upload bike picture

		protected void UplBikePicture_UploadedComplete(Object sender, AsyncFileUploadEventArgs e)
		{
			const String ext = ".jpg.jpeg.gif.png.bmp";

			if (!ext.Contains(Path.GetExtension(UplBikePicture.PostedFile.FileName).ToLower()))
			{
				return;
			}

			Item item = new Item(SelectedBikeId);

			try
			{
				UploadManager.SavePicture(item, UplBikePicture.PostedFile);

				ImgBikePicture.ImageUrl += "?" + DateTime.Now.Minute;
			}
			catch (Exception ex)
			{
				ErrorManager.Log(ex, "Could not save item picture.");
			}
		}

		#endregion
	}
}